package net.zjitc.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2017/2/27.
 */
@Controller
@Scope("prototype")//使用此注解，spring可以创建多个对象，默认情况只创建一个
public class UserAction extends ActionSupport implements ModelDriven<User>{
    private Log log=LogFactory.getLog(this.getClass());
    private String message;

    private User model = new User();

    @Resource
    private UserService userService;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
/*
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }*/
    /*登录界面
    * */

    /**
     * 登录界面，返回登录界面视图
     * @return
     */
    public String loginUI(){
        return "loginUI";
    }

//    登录
    public String login(){
        //如果有用户的话，返回登录成功
        User user=userService.findByUsernamePassword(model.getUsername(),model.getPassword());
        /*放入值栈空间的对象栈中*/
//        ActionContext.getContext().getValueStack().push(user);
        ActionContext.getContext().getSession().put("user",user);
        if (user != null){
//            message = "登录成功！";
            log.debug("登陆成功");
            log.info("登录成功！欢迎。。。");
            this.addActionMessage("登陆成功");
            /*查询所有用户*/
            List<User> userList =userService.findAll();
            /*将查找出来的对象放到值栈空间中*/
            ActionContext.getContext().put("userList",userList);

            return "loginSuccess";
        }
        //否则返回登录失败
        this.addFieldError(user.getUsername(),"用户名错误");
        message = "用户名或密码错误！";
        return  "loginFail";
    }

    @Override
    public User getModel() {
        return model;
    }
}
